package com.workcell.workdata.im.component.redis.base;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class LongRedisTemplate extends RedisTemplate<String,Long> implements RedisSerializer<Long>{
    public LongRedisTemplate(RedisConnectionFactory connectionFactory) {

        this.setKeySerializer(RedisSerializer.string());
        this.setHashKeySerializer(RedisSerializer.string());

        this.setValueSerializer(this);
        this.setHashValueSerializer(this);

        setConnectionFactory(connectionFactory);
        afterPropertiesSet();
    }

    @Override
    public byte[] serialize(Long aLong) throws SerializationException {
        if (aLong == null){
            return null;
        }
        return aLong.toString().getBytes();
    }

    @Override
    public Long deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null){
            return null;
        }
        return Long.parseLong(new String(bytes));
    }

    public List<Long> findList(String key){
        BoundSetOperations<String,Long> operations = super.boundSetOps(key);
        Set<Long> uidSet = operations.members();
        if (CollectionUtils.isEmpty(uidSet)){
            return new LinkedList<>();
        }
        return new LinkedList<>(uidSet);
    }

    public void add(String key, Collection<Long> idList) {
        if (idList.isEmpty()){
            return;
        }
        BoundSetOperations<String, Long> operations = super.boundSetOps(key);
        operations.add(idList.toArray(new Long[0]));
    }

    public void add(String key, Long id) {
        if (id == null){
            return;
        }
        super.boundSetOps(key).add(id);
    }

    public void remove(String key, Long id) {
        if (id == null){
            return;
        }
        super.boundSetOps(key).remove(id);
    }
}
